// utils/request.js
import config from './config'

const request = (url, method = 'GET', data = {}, headers = {}) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token') || ''  // 从本地缓存读取 token

    wx.request({
      url: config.baseUrl + url,
      method: method,
      data: data,
      timeout: config.timeout,
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token,
        ...headers
      },
      success: res => {
        const { code, msg } = res.data

        // 若依默认接口返回格式：{ code: 200, msg: "操作成功", data: {...} }
        if (code === 200) {
          resolve(res.data)
        } else if (code === 401) {
          wx.showToast({
            title: '未登录或登录失效',
            icon: 'none'
          })
          // 可引导用户重新登录
          reject(res.data)
        } else {
          wx.showToast({
            title: msg || '请求失败',
            icon: 'none'
          })
          reject(res.data)
        }
      },
      fail: err => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 快捷方法封装
const get = (url, data = {}, headers = {}) => request(url, 'GET', data, headers)
const post = (url, data = {}, headers = {}) => request(url, 'POST', data, headers)
const put = (url, data = {}, headers = {}) => request(url, 'PUT', data, headers)
const del = (url, data = {}, headers = {}) => request(url, 'DELETE', data, headers)

export default {
  request,
  get,
  post,
  put,
  delete: del
}
